package main

import (
	"time"
	"fmt"
)

//生产者
func generate() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

//消费者工厂
func createWorker(id int) chan int {
	in := make(chan int)
	doWork(id, in)
	return in
}

//消费者
func doWork(id int, in chan int) {
	go func() {
		for t := range in {
			time.Sleep(2 * time.Millisecond)
			fmt.Printf("%d,%d \n", id, t)
		}
	}()
}

func main() {
	c1, c2 := generate(), generate()
	worker := createWorker(0)
	end := time.After(80 * time.Millisecond)
	tick := time.Tick(time.Millisecond)
	var values []int
	for {
		var activeWorker chan int
		activeValue := 0
		if len(values) > 0 {
			activeWorker = worker
			activeValue = values[0]
		}
		select {
		case n := <-c1:
			values = append(values, n)
		case n := <-c2:
			values = append(values, n)
		case activeWorker <- activeValue:
			values = values[1:]
		case <-time.After(3 * time.Millisecond):
			fmt.Println("timed out")
		case <-tick:
			fmt.Printf("the array contains %d elements \n", len(values))
		//	fmt.Println(values)
		case <-end:
			fmt.Println("bye")
			return
		}
	}

}
